import { _decorator, Component, Node, ScrollView, instantiate, find, Label, Button, director } from "cc";
import event from "../utils/event";
import request from "../utils/request";
const { ccclass, property } = _decorator;

type ServerInfo = {
    id: string;
    name: string;
    url: string;
};

@ccclass("Server/Server")
export class Server extends Component {
    @property(Node)
    private serverListContent: Node = null;

    @property(Node)
    private serverListItem: Node = null;

    private servers: ServerInfo[] = [];

    start() {
        request("/servers/list").then(({ code, message, data }) => {
            this.servers = data;

            this.servers.forEach((server) => {
                const item = instantiate(this.serverListItem);
                item.active = true;
                item.on(Button.EventType.CLICK, this.handleStartGame.bind(this, server));
                find("server-name", item).getComponent(Label).string = server.name;
                this.serverListContent.addChild(item);
            });
        });
    }

    handleStartGame(server) {
        console.log(server);
        director.loadScene("game", this.onSceneLaunched.bind(this, server));
    }

    onSceneLaunched(server, error, scene) {
        setTimeout(() => {
            console.log("onSceneLaunched", scene, server);
            event.emit("game::enter", server);
        }, 0);
    }

    handleBackToHomeScene() {
        director.loadScene("home");
    }
}
